import React, { useState } from 'react';
import components from '@/components/demo';
import { getDefaultDemoKey, saveDefaultDemoKey } from '@/lib/tools';
import styles from './styles.module.less';

export default () => {
  // 管理开始时临时的demo页面key
  const defaultValue = getDefaultDemoKey() || 'Example';
  const [demoKey, saveDemoKey] = useState(defaultValue);

  const c = Object.entries(components).map((i) => {
    const [name, demo] = i;
    return { name, demo };
  });

  /**
   * 切换example
   *
   * @param {*} e
   */
  const onClick = (e) => {
    const key = e?.target?.innerText;
    if (key) {
      saveDemoKey(key);
      saveDefaultDemoKey(key);
    }
  };

  // 计算出demo
  const Demo = c.find((i) => i.name === demoKey)?.demo;

  return (
    <div className={styles.home}>
      <div className={styles.tabs}>
        <div className={styles.tips}>切换测试模块：</div>
        <div className={styles.item}>
          {Object.keys(components).map((i) => (
            <div value={i} key={i} className={i === demoKey ? styles.radioActive : styles.radio} onClick={onClick}>
              {i}
            </div>
          ))}
        </div>
      </div>
      <div className={styles.demo}>
        <Demo />
      </div>
    </div>
  );
};
